<?php

/**
 * main actions.
 *
 * @package    tvpv
 * @subpackage main
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 9301 2008-05-27 01:08:46Z dwhittle $
 */
class mainActions extends sfActions
{
	/**
	 * Executes index action
	 *
	 * @param sfRequest $request A request object
	 */
	public function executeIndex($request)
	{
		//$this->forward('default', 'module');
	}

	public function executeArticulos($request){
		/*if( $request->getParameter('page'))
		 $this->articulos_List = ArticuloPeer::getArtByCategoria($request->getParameter('page'),$request->getParameter('cat'));
		 else*/
		$this->articulosList = ArticuloPeer::getArtByCategoria($request->getParameter('cat'), $request->getParameter('orden'),  $request->getParameter('page'));
		//$this->articulosList = ProductsPeer::get
		//$this->redirect('main/articulos');
	}

	public function executeBuscar($request){
		//$this->articulosList = ArticuloPeer::getArtBySearch($this->getRequestParameter('search'), $request->getParameter('orden'), $request->getParameter('page'));
		$this->articulosList = ArticuloPeer::getArtBySearch($this->getRequestParameter('search'), $request->getParameter('orden'), $request->getParameter('page'));
	}

	public function executeShow($request){
		$this->formulario = new FormularioArticulo($this->getRequestParameter('id'));
		$this->forward404Unless($this->getRequestParameter('id'));
		if($request->isMethod('post'))
		{
			$this->formulario->bind($request->getParameter('articulo'));
			if ($this->formulario->isValid())
			{
				$art = ArticuloPeer::retrieveByPK($this->getRequestParameter('id'));
				$tmp = $this->getUser()->getAttribute('articulos');
				//if ( ( $art->getExistencia() - $tmp[$this->getRequestParameter('id')]['cantidad']) >= $this->formulario->getValue('cantidad'))
				{
					$this->getUser()->setFlash('validado',"Artículo agregado a la Bolsa");
					$this->agregarArticulo($this->formulario->getValues());
				}
				//else
				//$this->getUser()->setFlash('validado',"Error: Solo hay {$art->getExistencia()} Artículos en Existencia");*/
				//$this->redirect('main/show?id=4');
			}
			else
			$this->getUser()->setFlash('validado',"Error al Procesar");
		}
		//$this->articulo = ArticuloPeer::retrieveByPK($this->getRequestParameter('id'));
		$this->articulo = ProductsPeer::retrieveByPK($this->getRequestParameter('id'));
		$this->relacionados = ArticuloPeer::getRelacionados($this->getRequestParameter('id'));
	}

	public function agregarArticulo($datos){
		$articuloList = $this->getUser()->getAttribute('articulos');
		/*if($datos['color'])
		{
			$datos['id'] = $datos['color'];
			$datos['color'] = ArticuloPeer::retrieveByPK($datos['id'])->getColor();
		}
		if($datos['talla']){
			$datos['id'] = $datos['talla'];
			$datos['talla'] = ArticuloPeer::retrieveByPK($datos['id'])->getTalla();
		}*/

		if( empty( $articuloList))
		{
			$articuloList[$datos['id']] = $datos;

		}
		else
		{
			if( array_key_exists( $datos['id'] ,$articuloList) ){
				$articuloList[ $datos['id'] ]["cantidad"] += $datos['cantidad'];
			}
			else
			$articuloList[$datos['id']] = $datos;
			//$this->getUser()->getAttribute('articulos');
			//$this->getUser()->setAttribute('articulos',$datos);
			//$articuloList = $datos;
		}
			
		$cantidad = $this->getUser()->getAttribute('cantidad',0);
		$total = $this->getUser()->getAttribute('total',0);
		$total += ( $datos['precio'] * $datos['cantidad']);
		$cantidad += $datos['cantidad'];
			
		$this->getUser()->setAttribute('cantidad',$cantidad);
		$this->getUser()->setAttribute('total',$total);
		$this->getUser()->setAttribute('articulos',$articuloList);
	}

	public function executeSuscribir($request){
		$this->forward404Unless($request->isMethod('post'));
		//$email = $request->getParameter('email');
		$email = $this->getRequestParameter('email');
		$c = new Criteria();
		$c->add(SuscripcionPeer::EMAIL, $email);
		$suscripcion = SuscripcionPeer::doSelectOne($c);

		if ($this->getRequestParameter('suscribir') == 'Off')
		{
			$suscripcion->delete();
		}
		if ($this->getRequestParameter('suscribir') == 'On')
		{
			if($suscripcion == NULL ){
				$this->form = new SuscripcionForm();
				$this->form->bind(array('email'=>$email));
				if($this->form->isValid()){
					$this->form->save();
				}
				else
				{
					$this->error = "Email Invalido";
				}

			}
		}
		$this->setTemplate('index');
	}

	public function executeAutocompletar($request){
		$c = new Criteria();
		$c->add(ProductsPeer::NAME,$request->getParameter('search')."%",Criteria::LIKE);
		//$c->add(ArticuloPeer::NOMBRE,$request->getParameter('search')."%",Criteria::LIKE);
		$this->autocompletar = ProductsPeer::doSelect($c);
		return $this->renderPartial('autocompletar');
	}

	public function executeRecomendar( sfWebRequest $request)
	{
		$this->formRecomendar = new FormularioRecomendar();
		if($request->isMethod('post'))
		{
			$articulo = ArticuloPeer::retrieveByPK($request->getParameter('id'));
			//require("class.phpmailer.php");
			//require("class.smtp.php");

			$mail = new PHPMailer();
			//$mail->Mailer= "sendmail";

			//$mail->PluginDir = "";
			$mail->CharSet = "utf8";
			//$mail->IsSMTP();
			//$mail->Username = "perfe08n";
			//$mail->Password = "cambiame";
			//$mail->Port = 465;
			//$mail->SMTPAuth = true;
			//$mail->SMTPDebug=false;
			//$mail->SMTPSecure = "ssl";
			$mail->Host = "localhost";

			$mail->From = 'wario@wario.com';
			$mail->FromName = "BellaJoia";
			$mail->Subject = "Su amigo le recomendo";
			//$mail->AddAddress("asalgado@smar-t.com.mx","Alejandro Salgado");
			$mail->AddAddress("wario.mvc@gmail.com","Mario Valenzuela");

			$contenido = "<font face='Arial, Helvetica, sans-serif' size='4'><br>";
			$contenido .= "<h3>Comentarios enviados desde el formulario \nde la P&aacute;gina www.grupomargo.com.mx</h3><br>";
				

			$mail->Body = $contenido;
			$mail->AltBody = "Mensaje";
			$mail->IsHTML(true);
			$enviado = $mail->Send();
			$this->getUser()->setFlash('validado','Recomendacion Enviada');
			$this->formRecomendar->bind($request->getParameter('datos'));
			if ($this->formRecomendar->isValid())
			$this->redirect("main/show?id=".$request->getParameter('id'));
		}
		else
		{
				
		}
	}

	public function executeTest(sfWebRequest $request){
		$p = ProductsPeer::retrieveByPK($request->getParameter('id'));
		if ($p->getImage() != null){
			$response = $this->getResponse();
			$response->clearHttpHeaders();
			$response->setContentType('image/png');
			$response->setContent(stream_get_contents($p->getImage()));
		}
		else
		{
			$res = imagecreatefrompng(sfConfig::get('sf_root_dir').'/web/images/fotos/none.png');
			$response = $this->getResponse();
      $response->clearHttpHeaders();
      $response->setContentType('image/png');
      $response->setContent(imagepng($res));
		}
		return sfView::NONE;
	}
	
  public function executeGetPicCat(sfWebRequest $request){
    $p = CategoriesPeer::retrieveByPK($request->getParameter('id'));
    if ($p->getImage() != null){
      $response = $this->getResponse();
      $response->clearHttpHeaders();
      $response->setContentType('image/png');
      $response->setContent(stream_get_contents($p->getImage()));
    }
    else
    {
      $res = imagecreatefrompng(sfConfig::get('sf_root_dir').'/web/images/fotos/none.png');
      $response = $this->getResponse();
      $response->clearHttpHeaders();
      $response->setContentType('image/png');
      $response->setContent(imagepng($res));
    }
    return sfView::NONE;
  }
}
